'use strict';
const CMSCONFIG = require('./config/cms.config');

module.exports = (app) => {
	app.beforeStart(async () => {
		const ctx = app.createAnonymousContext();
		// 初始化角色与用户
		console.log('初始化角色与用户');
		let adminRole = await ctx.model.Role.findOne({ name: '超级管理员' });
		let ordinarylRole = await ctx.model.Role.findOne({ name: '普通用户' });
		let user = await ctx.service.user.findRoot();
		let tag = await ctx.model.Tag.findOne({ default: true });
		console.log(tag)
		if (!tag) {
			tag = await ctx.model.Tag.create({ name: '默认分类', default: true });
		}
		if (!adminRole) {
			console.log('没有超级管理员角色，新增');
			// 传入false用于绕过角色认证
			adminRole = await ctx.model.Role.create({ name: '超级管理员' });
		}
		if (!ordinarylRole) {
			console.log('没有普通用户角色，新增');
			// 传入false用于绕过角色认证
			ordinarylRole = await ctx.model.Role.create({ name: '普通用户' });
		}
		if (!app.custom) {
			app.custom = {}
		}
		app.custom.role = {
			admin: adminRole._id,
			ordinarylRole: ordinarylRole._id,
		}
		app.custom.defaultTag = tag
		if (!user) {
			console.log('没有超级用户，新增');
			const { username, password, name } = CMSCONFIG.admin;
			user = await ctx.service.user.create({ username, password, name, root: true });
			console.log('新增成功，添加超级管理员权限');
			await ctx.service.user.update(user.id, {
				$addToSet: {
					role: adminRole.id
				}
			});
		}
		app.custom.admin = user
		// 将路由列表存入数据库
		console.log('将路由列表存入数据库');
		let routers = app.getRouters;
		for (let i of routers) {
			if (i.name && i.name.includes('_power')) {
				await ctx.service.router.create({
					methods: i.methods,
					name: i.name,
					path: i.path
				});
			}
		}

		// 去除所有空格
		String.prototype.trimAll = function () {
			return this.replace(/\s+/g, '');
		};
	});
	// 自定义校验规则
	app.validator.addRule('objectId', (rule, value) => {
		const reg = /^\w{24}$/;
		if (value.length != '' && !reg.test(value)) {
			return '必须是一个正确的ID';
		}
	});
};
